package com.sxbbc.common.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.CashTypeEnums;
import com.sxbbc.common.core.mapper.jz.BankDetailMapper;
import com.sxbbc.common.core.mapper.jz.BankTypeMapper;
import com.sxbbc.common.core.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.function.common.GetRest;
import com.function.common.RestResponse;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 银行卡信息 服务实现类
 * </p>
 *
 * @author xiaoky
 * @since 2019-05-31
 */
@Service
public class BankDetailServiceImpl extends ServiceImpl<BankDetailMapper, BankDetail> implements IBankDetailService {
    @Autowired
    private BankTypeMapper bankTypeMapper;
    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private BankDetailMapper bankDetailMapper;
    @Autowired
    private ICCustomerAuthenService customerAuthenService;
    @Autowired
    private IAgAgentService agAgentService;
    @Autowired
    private BBusinessService bBusinessService;

    @Override
    public List<BankDetail> queryBankDetailList(Integer targetId, Integer type) {
        BankDetail bankDetail = new BankDetail();
        bankDetail.setTargetId(targetId);
        bankDetail.setType(type);
        QueryWrapper<BankDetail> wrapper = queryWrapper(bankDetail);
        List<BankDetail> bankDetailList = super.list(wrapper);
        for (BankDetail bank : bankDetailList) {
            String code = bank.getBankCard();
            if (code.length() > 4) {
                bank.setLastCode(code.substring(code.length() - 4, code.length()));
            } else {
                bank.setLastCode(code);
            }
        }
        return bankDetailList;
    }

    /**
     * 银行卡查询条件
     *
     * @param bankDetail
     * @return
     */
    @Override
    public QueryWrapper<BankDetail> queryWrapper(BankDetail bankDetail) {
        QueryWrapper<BankDetail> wrapper = new QueryWrapper<BankDetail>();
        if (bankDetail.getTargetId() != null) {
            wrapper.eq("target_id", bankDetail.getTargetId());
        }
        if (bankDetail.getType() != null) {
            wrapper.eq("type", bankDetail.getType());
        }
        if (bankDetail.getTypeId() != null) {
            wrapper.eq("type_id", bankDetail.getTypeId());
        }
        wrapper.orderByAsc("create_time");
        return wrapper;
    }

    @Override
    public RestResponse detailBankDetail(Integer targetId, Integer bankDetailId, Integer type) {
        BankDetail bankDetail = super.getById(bankDetailId);
        if (bankDetail == null) {
            return GetRest.getFail("银行卡不存在,删除失败");
        }

        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        // 银行卡归属类型，目标id判断
        if (calcuUtils.isEquals(type, bankDetail.getType())
                && calcuUtils.isEquals(bankDetail.getTargetId(), bankDetail.getTargetId())) {
            boolean result = super.removeById(bankDetailId);
            if (result) {
                return GetRest.getSuccess("删除成功");
            }
        }
        return GetRest.getFail("删除失败");
    }

    @Override
    public RestResponse editBankDetail(BankDetail detail) {
        if (StringUtils.isEmpty(detail.getRealName())) {
            return GetRest.getFail("请输入持卡人姓名");
        }
        if (StringUtils.isEmpty(detail.getIdcard())) {
            return GetRest.getFail("请输入身份证号码");
        }
        if (StringUtils.isEmpty(detail.getBankCard())) {
            return GetRest.getFail("请输入银行卡号");
        }
        BankType bankType = bankTypeMapper.selectById(detail.getTypeId());
        if (bankType == null) {
            return GetRest.getFail("请选择开户行");
        }
        if (StringUtils.isBlank(detail.getBankAddr())) {
            return GetRest.getFail("请输入开户支行");
        }
        if (StringUtils.isEmpty(detail.getPhone())) {
            return GetRest.getFail("请输入预留手机号");
        }
        detail.setBankName(bankType.getBankName());
        detail.setLogo(bankType.getLogo());

        //相同银行卡号不能重复添加
        QueryWrapper<BankDetail> qwbd = new QueryWrapper<BankDetail>();
        qwbd.eq("bank_card", detail.getBankCard()).eq("target_id", detail.getTargetId()).eq("type", detail.getType());
        if (super.count(qwbd) > 0) {
            return GetRest.getFail("该银行卡已经添加,不能重复添加");
        }

        //用户身份证必须和认证的身份证符合
        if (CalcuUtils.getInstance().isEquals(detail.getType(), CashTypeEnums.CUSTOMER.getId())) {
//            QueryWrapper<CCustomerAuthen> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("cid", detail.getTargetId());
//            CCustomerAuthen authen = customerAuthenService.getOne(queryWrapper);
//            if (authen == null) {
//                return GetRest.getFail("请先进行实名认证");
//            }
//            if (!CalcuUtils.getInstance().isEquals(authen.getStatus(), StaticUtils.STATUS_SUCCESS)) {
//                return GetRest.getFail("实名认证受理中，当前不可添加银行卡");
//            }
//            if (!authen.getIdcard().equals(detail.getIdcard())) {
//                return GetRest.getFail("身份证号与实名认证的身份证号不一致");
//            }
//            if (!authen.getRealName().equals(detail.getRealName())) {
//                return GetRest.getFail("所填姓名与实名认证的真实姓名不一致");
//            }
            //检测该用户是否绑定过银行卡，没有绑定需要验证银行四元素
            //认证类型 1身份证验证 2港澳证件
            //验证银行四元素
            RestResponse validBankcode = CalcuUtils.getInstance().validBankcode4(detail.getRealName(),
                    detail.getIdcard(), detail.getBankCard(), detail.getPhone());
            if (!validBankcode.isStatus()) {
                return validBankcode;
            }else{
                Object data = validBankcode.getData();
                if(data instanceof  JSONObject){
                    JSONObject cus=(JSONObject)data;
                    CCustomer customer = icCustomerService.getById(detail.getTargetId());
                    if(customer!=null){
                        customer.setAuthen(StaticUtils.STATUS_YES);
                        customer.setRealName(cus.getString("name"));
                        icCustomerService.updateById(customer);
                    }
                }
            }
        } else if (CalcuUtils.getInstance().isEquals(detail.getTypeId(), CashTypeEnums.BUSINESS.getId())) {
            BBusiness business = bBusinessService.getById(detail.getTargetId());
            if (business == null) {
                return GetRest.getFail("用户信息获取失败，请检查网络");
            }
//            QueryWrapper<CCustomerAuthen> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("cid", business.getCid());
//            CCustomerAuthen authen = customerAuthenService.getOne(queryWrapper);
//            if (authen == null || !CalcuUtils.getInstance().isEquals(authen.getStatus(), StaticUtils.STATUS_SUCCESS)) {
//                return GetRest.getFail("请先完成实名认证");
//            }
//            if (!authen.getIdcard().equals(detail.getIdcard())) {
//                return GetRest.getFail("身份证号与实名认证的身份证号不一致");
//            }
//            if (!authen.getRealName().equals(detail.getRealName())) {
//                return GetRest.getFail("所填姓名与实名认证的真实姓名不一致");
//            }
            //检测该用户是否绑定过银行卡，没有绑定需要验证银行四元素
            //认证类型 1身份证验证 2港澳证件
//            if (authen.getAuthType().equals(1)) {
            //验证银行四元素
            RestResponse validBankcode = CalcuUtils.getInstance().validBankcode4(detail.getRealName(), detail.getIdcard(),
                    detail.getBankCard(), detail.getPhone());
            if (!validBankcode.isStatus()) {
                return validBankcode;
            }
//            }
        } else if (CalcuUtils.getInstance().isEquals(detail.getTypeId(), CashTypeEnums.AGENT.getId())) {
            AgAgent agent = agAgentService.getById(detail.getTargetId());
            if (agent == null) {
                return GetRest.getFail("用户信息获取失败，请检查网络");
            }
        }
        boolean result = super.saveOrUpdate(detail);
        if (result) {
            return GetRest.getSuccess("保存成功");
        }
        return GetRest.getFail("保存失败");
    }

    @Override
    public List<BankDetail> queryByTagetId(Integer targetid) {

        List<BankDetail> bankDetails = bankDetailMapper.queryBankDetailByTargetId(targetid);
        return bankDetails;
    }

}
